package org.bdware.repository.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;

public class Utils {
    public static String getFileName(String downloadUrl) {
        String[] urlInfo = downloadUrl.split("\\/");
        return urlInfo[urlInfo.length - 1];
    }

    public static byte[] getFileBytes(String path){
        File file = new File(path);
        int length = (int) file.length();
        byte[] data = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            data = inputStream2Byte(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return data;
        }
    }

    public static byte[] getFileFromRemote(String downloadUrl){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        byte[] data = null;
        HttpGet httpGet = new HttpGet(downloadUrl);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            data = inputStream2Byte(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return  data;
        }
    }


    public static byte[] inputStream2Byte(InputStream is) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while((rc = is.read(buff,0,100)) > 0){
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
